package com.situ.day20;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ClassDemo {
    @Test
    public void test1() throws ClassNotFoundException {
        //1.Class.forName("包名+类名")
        Class clazz1 = Class.forName("com.situ.day20.Student");
        //2.类名.class
        Class clazz2 = Student.class;
        //3.对象.getClass()
        Student student = new Student();
        Class clazz3 = student.getClass();

        System.out.println(clazz1 == clazz2);//true
        System.out.println(clazz1 == clazz3);//true
        System.out.println(clazz2 == clazz3);//true
    }

    @Test
    public void test2() throws NoSuchMethodException {
        Class clazz = Student.class;
        Constructor[] constructors = clazz.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
            System.out.println(constructor.getName());
            System.out.println(constructor.getModifiers());

        }
        System.out.println("--------------------");
        Constructor constructor1 = clazz.getConstructor();
        System.out.println(constructor1);
        System.out.println("--------------------");
        // (Class... parameterTypes )
        Constructor constructor2 = clazz.getConstructor(Integer.class, String.class, Integer.class, String.class);
        System.out.println(constructor2);
    }

    @Test
    public void test3() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class clazz = Student.class;
        //private Student(Integer id, String name, Integer age, String gender)
        Constructor constructor = clazz.getDeclaredConstructor(Integer.class, String.class, Integer.class, String.class);
        System.out.println(constructor);
        //在反射面前，私有的都可以访问
        constructor.setAccessible(true);
        //Student student = new Student(1, "zhansgan", 23, "男");
        Student student = (Student) constructor.newInstance(1, "zhansgan", 23, "男");
        System.out.println(student);

    }

    @Test
    public void test44() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //Student student = new Student();
        //student.setName("lisi");
        Class clazz = Student.class;
        Constructor constructor = clazz.getConstructor();
        Student student = (Student) constructor.newInstance();
        Method method = clazz.getMethod("setName", String.class);
        method.invoke(student, "lisi");
        System.out.println(student);
    }
}
